package com.mianle.userapi.util;

import com.fasterxml.jackson.databind.JsonNode;
import org.apache.http.HttpStatus;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpUriRequest;
import org.apache.http.client.utils.HttpClientUtils;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.Assert;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * http工具类
 * <p>
 * <b>创建日期：</b> 2015年10月26日
 * </p>
 * 
 * @author wangqiangliang
 * @since 0.0.1
 */
public class HttpUtil {

	private static final Logger log = LoggerFactory.getLogger(HttpUtil.class);

	/**
	 * http请求
	 * 
	 * @param request
	 * @return
	 */
	private static String request(HttpUriRequest request) {
		Assert.notNull(request,"requst is null");
		String result = null;
		CloseableHttpClient httpClient = HttpClientBuilder.create().build();
		CloseableHttpResponse response = null;
		try {
			response = httpClient.execute(request);
			StatusLine statusLine = response.getStatusLine();	
			if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
				result = EntityUtils.toString(response.getEntity(), "UTF-8");
			} else {
				log.error("http response error, StatusCode: {}, Reason: {}",
						statusLine.getStatusCode(), statusLine.getReasonPhrase());
			}
		} catch (ClientProtocolException e) {
			log.error("协议异常, cause: ", e);
		} catch (IOException e) {
			log.error("IO异常, cause: ", e);
		} finally {
			HttpClientUtils.closeQuietly(response);
			HttpClientUtils.closeQuietly(httpClient);
		}
		return result;
	}

	/**
	 * HttpGet报文发送
	 * 
	 * @param url
	 * @return
	 */
	public static String get(String url) {
//		log.info("http get url: {}", url);
		HttpGet httpGet = new HttpGet(url);
		String result = request(httpGet);
//		log.info("http get result: {}", result);
		return result;
	}

	/**
	 * HttpGet报文发送
	 * 
	 * @param httpGet
	 * @return
	 */
	public static String get(HttpGet httpGet) {
		Assert.notNull(httpGet,"httpget is null");
//		log.info("http get url: {}", httpGet.getURI());
//		log.info("http get headers: {}", StringUtils.join(httpGet.getAllHeaders(), ';'));
		String result = request(httpGet);
//		log.info("http get result: {}", result);
		return result;
	}

	/**
	 * HttpPost报文发送
	 * 
	 * @param url
	 * @return
	 */
	public static String post(String url) {
//		log.info("http post url: {}", url);
		HttpPost httpPost = new HttpPost(url);
		String result = request(httpPost);
//		log.info("http post result: {}", result);
		return result;
	}

	/**
	 * HttpPost报文发送
	 * 
	 * @param url
	 * @return
	 */
	public static String post(String url, String entity) {
//		log.info("http post url: {}", url);
//		log.info("http post entity: {}", entity);
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new StringEntity(entity, "UTF-8"));
		String result = request(httpPost);
//		log.info("http post result: {}", result);
		return result;
	}

	/**
	 * HttpPost报文发送
	 * 
	 * @param url
	 * @return
	 */
	public static String post(String url, JsonNode json) {
//		log.info("http post url: {}", url);
//		log.info("http post json: {}", json.toString());
		HttpPost httpPost = new HttpPost(url);
		httpPost.setEntity(new StringEntity(json.toString(), "UTF-8"));
		String result = request(httpPost);
//		log.info("http post result: {}", result);
		return result;
	}



	/**
	 * 获取当前网络ip
	 * @param request
	 * @return
	 */
	public static String getIpAddr(HttpServletRequest request){
		String ipAddress = request.getHeader("x-forwarded-for");
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("Proxy-Client-IP");
		}
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getHeader("WL-Proxy-Client-IP");
		}
		if(ipAddress == null || ipAddress.length() == 0 || "unknown".equalsIgnoreCase(ipAddress)) {
			ipAddress = request.getRemoteAddr();
			if(ipAddress.equals("127.0.0.1") || ipAddress.equals("0:0:0:0:0:0:0:1")){
				//根据网卡取本机配置的IP
				InetAddress inet=null;
				try {
					inet = InetAddress.getLocalHost();
				} catch (UnknownHostException e) {
					e.printStackTrace();
				}
				ipAddress= inet.getHostAddress();
			}
		}
		//对于通过多个代理的情况，第一个IP为客户端真实IP,多个IP按照','分割
		if(ipAddress!=null && ipAddress.length()>15){ //"***.***.***.***".length() = 15
			if(ipAddress.indexOf(",")>0){
				ipAddress = ipAddress.substring(0,ipAddress.indexOf(","));
			}
		}
		return ipAddress;
	}

}
